package io.itit.ecp.admin.server.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import icu.mhb.mybatisplus.plugln.base.service.impl.JoinServiceImpl;
import io.itit.ecp.admin.common.enums.IEnergyTypeEnums;
import io.itit.ecp.admin.server.entity.CarbonEmissionPlanDataEntity;
import io.itit.ecp.admin.server.entity.CarbonEmissionPlanDetailEntity;
import io.itit.ecp.admin.server.entity.CarbonEmissionPlanEntity;
import io.itit.ecp.admin.server.entity.extend.CarbonEmissionPlanExtEntity;
import io.itit.ecp.admin.server.mapper.CarbonEmissionPlanDataMapper;
import io.itit.ecp.admin.server.service.ICarbonEmissionPlanDataService;
import io.itit.grass.common.server.helper.ThreadPoolHelper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.time.ZoneId;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * <p>
 *
 * @Author：Roy
 * @Description：碳排放规划数据服务实现类
 * @Date：Create by 2024-01-17 17:59:59
 */
@Service
@Slf4j
public class CarbonEmissionPlanDataServiceImpl extends JoinServiceImpl<CarbonEmissionPlanDataMapper, CarbonEmissionPlanDataEntity> implements ICarbonEmissionPlanDataService {

    @Override
    public void saveData(CarbonEmissionPlanExtEntity planEntity) {
        ThreadPoolHelper.i().execute(() -> build(planEntity, 0));
    }

    public void build(CarbonEmissionPlanExtEntity planEntity, int count) {
        try {
            List<Date> solidifyDateList = getSolidifyDateList(planEntity.getEffectiveTimeStart(), planEntity.getEffectiveTimeEnd());
            List<CarbonEmissionPlanDataEntity> resultList = new ArrayList<>();
            for (Date solidifyDate : solidifyDateList) {
                for (IEnergyTypeEnums.Type value : IEnergyTypeEnums.Type.values()) {
                    for (CarbonEmissionPlanDetailEntity planDetailEntity : planEntity.getPlanDetailList()) {
                        save(planEntity, solidifyDate, value.type, planDetailEntity, resultList);
                    }
                }
            }
            if (CollectionUtils.isNotEmpty(resultList)) {
                this.saveBatch(resultList);
            }
        } catch (Exception e) {
            if (count < 2) {
                build(planEntity, count + 1);
            }
            log.error("规划数据入库失败！第{}次", count, e);
        }
    }

    private void save(CarbonEmissionPlanEntity planEntity, Date solidifyDate, String value, CarbonEmissionPlanDetailEntity planDetailEntity, List<CarbonEmissionPlanDataEntity> resultList) {
        CarbonEmissionPlanDataEntity dataEntity = new CarbonEmissionPlanDataEntity();
        dataEntity.setSolidifyDate(solidifyDate);
        dataEntity.setSceneProjectId(planEntity.getSceneProjectId());
        dataEntity.setSceneEdificeId(planEntity.getSceneEdificeId());
        if (value.equals(IEnergyTypeEnums.Type.cold.type)) {
            dataEntity.setCarbonEmission(planDetailEntity.getCold());
        } else if (value.equals(IEnergyTypeEnums.Type.water.type)) {
            dataEntity.setCarbonEmission(planDetailEntity.getWater());
        } else {
            dataEntity.setCarbonEmission(planDetailEntity.getElectric());
        }
        dataEntity.setEnergyTypeId(value);
        dataEntity.setSceneFloorId(planDetailEntity.getSceneFloorId());
        resultList.add(dataEntity);
    }

    @Override
    public void delete(CarbonEmissionPlanEntity planEntity) {
        baseMapper.delete(new LambdaQueryWrapper<CarbonEmissionPlanDataEntity>()
                .eq(CarbonEmissionPlanDataEntity::getSceneProjectId, planEntity.getSceneProjectId())
                .eq(CarbonEmissionPlanDataEntity::getSceneEdificeId, planEntity.getSceneEdificeId())
                .ge(CarbonEmissionPlanDataEntity::getSolidifyDate, planEntity.getEffectiveTimeStart())
                .le(CarbonEmissionPlanDataEntity::getSolidifyDate, planEntity.getEffectiveTimeEnd())
        );
    }


    /**
     * 获取指定时间范围内的日期列表
     *
     * @param effectiveTimeStart 生效时间的起始日期
     * @param effectiveTimeEnd   生效时间的结束日期
     * @return 日期列表
     */
    public List<Date> getSolidifyDateList(Date effectiveTimeStart, Date effectiveTimeEnd) {
        List<Date> resultList = new ArrayList<>();
        // 将起始日期和结束日期转换为LocalDate类型
        LocalDate startTime = effectiveTimeStart.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
        LocalDate endTime = effectiveTimeEnd.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
        LocalDate currentDate = startTime;
        // 循环遍历起始日期到结束日期之间的每一天
        while (!currentDate.isAfter(endTime)) {
            // 将LocalDate类型的日期转换为Date类型，并添加到结果列表中
            resultList.add(Date.from(currentDate.atStartOfDay().atZone(ZoneId.systemDefault()).toInstant()));
            // 将当前日期加一天
            currentDate = currentDate.plusDays(1);
        }
        return resultList;
    }

    public static void main(String[] args) {
        System.out.println(test(0));
    }

    public static int test(int i) {
        if (i < 2) {
            test(i++);
        }
        return i;
    }

}